<template>
  <div class="container">
    <div class="push-container">
      <el-form
        label-position="left"
        class="check-form"
        :model="formData"
        :rules="rules"
        ref="formRef"
        label-width="80px"
        :show-message="false"
        status-icon
        :hide-required-asterisk="true"
        size="small"
      >
        <div class="header"><span class="header-icon"></span><span class="header-title">发布闲置</span></div>
        <div class="img-list">
          <div class="header-title" style="margin-top: 10px; margin-bottom: 15px; font-size: 18px">图片编辑</div>

          <el-upload
            v-model:file-list="fileList"
            action="http://127.0.0.1:8888/upload/image"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
          >
            <div style="line-height: 80px; font-size: 12px; color: #9999b3">+添加优质图</div>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img width="100%" w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </div>
        <div class="push-content">
          <el-form-item label-width="0" prop="title">
            <el-input
              style="margin-left: 15px"
              v-model="formData.title"
              maxlength="20"
              show-word-limit
              type="text"
              placeholder="填写商品标题，可能会更容易卖出哦~"
              class="input-title"
            />
          </el-form-item>
          <el-form-item label-width="0" prop="intro">
            <el-input
              style="margin-left: 15px"
              v-model="formData.intro"
              :rows="5"
              maxlength="200"
              show-word-limit
              type="textarea"
              placeholder="描述下宝贝的品牌型号、货品来源..."
              class="input-content"
            />
          </el-form-item>
        </div>
        <div class="btns">
          <!--          <button class="css-fm44j css-osq2ks dyn">-->
          <!--            <span class="btn-content"># 话题</span></button-->
 
          <!--          <button class="css-fm44j css-osq2ks dyn">-->
          <!--          <span class="btn-content"-->
          <!--          ><div class="smile"></div>-->
          <!--            表情</span-->
      
          <!--          </button>-->
          <el-form-item label="商品分类" prop="type" style="width: 200px">
            <el-select v-model="formData.type" placeholder="选择商品分类">
              <el-option
                v-for="item in menuList"
                :key="item.id"
                :label="item.typeName"
                :value="item.typeCode"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div style="margin-left: 20px">
          <el-divider style="width: 576px" />
        </div>
        <div>
          <div class="header-title" style="margin-top: 10px; margin-bottom: 15px; font-size: 18px; padding-left: 20px">
            发布设置
          </div>
          <div style="padding-left: 20px">
            <el-form-item label="宝贝位置">
              <div style="cursor: pointer; margin-left: 0; border-radius: 7px; color: #857679" @click="selectAdd">
                <el-icon><Location /></el-icon>
                {{ formData.province + ' ' + formData.city }}
                <el-icon><CaretRight /></el-icon>
              </div>
            </el-form-item>
            <el-form-item label="发货方式" prop="postType">
              <el-radio-group v-model="formData.postType" required>
                <el-radio value="0">邮寄</el-radio>
                <el-radio value="1">自提</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="价格">
              <el-input-number
                required
                controls-position="right"
                v-model="formData.price"
                :precision="2"
                :step="1"
                :min="0"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="原价">
              <el-input-number
                required
                controls-position="right"
                v-model="formData.originalPrice"
                :precision="2"
                :step="1"
                :min="0"
              ></el-input-number>
            </el-form-item>
          </div>
        </div>
        <div class="submit">
          <button class="publishBtn" type="submit" @click="publish">
            <span class="btn-content">发布</span>
          </button>
          <button class="clearBtn" @click="$router.push('/')">
            <span class="btn-content">取消</span>
          </button>
        </div>
      </el-form>
    </div>

    <!--抽屉 地址编辑-->
    <div>
      <el-drawer @close="closeDrawer" :show-close="false" v-model="drawer" direction="rtl">
        <address_edit @close-drawer="closeDrawer"></address_edit>
      </el-drawer>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import type { FormInstance, UploadFile, UploadFiles, UploadProps } from 'element-plus';
import { Location, CaretRight } from '@element-plus/icons-vue';
import { ElNotification } from 'element-plus';
import gdMapUtil from '@/utils/gdMapUtil';
import address_edit from './address_edit.vue';
import { getTypeList } from '@/api/productType';
import { createProductInfo } from '@/api/product';
import { login } from '@/api/user';

interface FormData {
  id: string;
  type: string;
  title: string;
  intro: string;
  image: string;
  price: number;
  originalPrice: number;
  postType: string;
  province: string;
  city: string;
  adcode: string;
  district?: string;
}
interface DialogState {
  visible: boolean;
  imageUrl: string;
}
interface MenuItem {
  id: number | string;
  typeName: string;
  typeCode: string;
}
const router = useRouter();
const formRef = ref<FormInstance>();
const drawer = ref(false);
const dialog = reactive<DialogState>({
  visible: false,
  imageUrl: '',
});
const fileList = ref<UploadFile[]>([]);
const menuList = ref<MenuItem[]>([]);
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
const formData = reactive<FormData>({
  id: '',
  type: '',
  title: '',
  intro: '',
  image: '',
  price: 0,
  originalPrice: 0,
  postType: '1',
  province: '',
  city: '',
  adcode: '',
});

// 表单验证规则
const rules = {
  postType: [{ required: true, message: '请选择发货方式~', trigger: 'blur' }],
  intro: [{ required: true, message: '有商品描述才能发布哦~', trigger: 'blur' }],
  title: [{ required: true, message: '有商品标题才能发布哦~', trigger: 'blur' }],
  type: [{ required: true, message: '选择商品分类才能发布哦~', trigger: 'blur' }],
};

const getMenuList = async () => {
  const res = await getTypeList();
  menuList.value = res.result;
};

const getCity = async () => {
  console.log(123);
  
  const res = await gdMapUtil.getCity();
  console.log(1223,res);
  
  formData.province = res.province;
  formData.city = res.city;
  formData.adcode = res.adcode;
};

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};


const selectAdd = () => {
  console.log(123);
  
  drawer.value = true;
  console.log(122,drawer.value);
  
};

const closeDrawer = async (changeAddress?: any) => {
  if (changeAddress) {
    const res = await gdMapUtil.GeocoderGetAddress(changeAddress.location.lng, changeAddress.location.lat);
    const { addressComponent } = res.regeocode;
    console.log(125,addressComponent);
    
    formData.adcode = addressComponent.adcode;
    formData.province = addressComponent.province;
    formData.city = addressComponent.city;
    formData.district = addressComponent.district;
  }
};

const publish = async () => {

  console.log(123);
  
  if (!formRef.value) return;

  // 如果文件列表中有文件，更新formData.image
  if (fileList.value.length > 0) {
    const _fileList = fileList.value.map((file: any) => file.response?.result?.url);
    formData.image = JSON.stringify(_fileList);
  }
console.log(1111,formData);

  // 验证表单，只有当验证成功时才继续
  try {
    await formRef.value.validate();

    
    // 只有当表单验证通过后，才调用API创建产品信息
    await createProductInfo(formData);
    router.push('/user')
    ElNotification({
      type: 'success',
      title: '爱吃咸红薯的鱼',
      message: '请等待审核通过',
    });
  } catch (error) {
    console.error('Form validation failed:', error);
    // 处理验证失败的情况，这里不应该有任何会导致页面跳转的行为
  }
};

// 生命周期钩子
onMounted(() => {
  getCity();
  getMenuList();
});

</script>
<style lang="less" scoped>
:deep(.push-content .el-input--mini .el-input__inner) {
  height: 40px;
}
.check-form .el-form-item__content {
  margin-left: 0 !important;
}
:deep(.el-drawer__header) {
  display: none;
}
:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 80px;
  height: 80px;
}
:deep(.el-upload-list__item.is-success .el-upload-list__item-status-label) {
  display: none;
}

:deep(.el-upload--picture-card) {
  width: 80px;
  height: 80px;
}

.container {
  flex: 1;
  padding-top: 72px;

  .push-container {
    margin-left: 12vw;
    width: 600px;
    border-radius: 8px;
    box-sizing: border-box;

    .header {
      padding: 15px 0;
      line-height: 16px;
      font-size: 16px;
      font-weight: 400;

      .header-icon {
        position: relative;
        top: 2px;
        display: inline-block;
        width: 6px;
        height: 19px;
        background: #3a64ff;
        border-radius: 3px;
        margin-right: 2px;
      }

      .header-title {
        line-height: 20px;
        font-size: 20px;
      }
    }

    .img-list {
      width: 540px;
      margin-left: 20px;
      padding: 0;
    }

    .push-content {
      padding: 10px 6px 10px 6px;
      position: relative;

      .scroll-tag-container {
        position: absolute;
        width: 98%;
        background-color: #fff;
        z-index: 99999;
        border: 1px solid #f4f4f4;
        height: 300px;
        overflow: auto;

        .scrollbar-tag-item {
          display: flex;
          align-items: center;
          height: 30px;
          margin: 10px;
          text-align: center;
          border-radius: 4px;
          padding-left: 2px;
          color: #484848;
          font-size: 14px;
        }

        .scrollbar-tag-item:hover {
          background-color: #f8f8f8;
        }
      }

      .input-title {
        height: 40px;
        margin-bottom: 5px;
        font-size: 12px;
      }

      .input-content {
        font-size: 12px;
      }
    }

    .btns {
      padding: 0 12px 0px 20px;

      button {
        min-width: 62px;
        width: 62px;
        margin: 0 6px 0 0;
        height: 18px;
      }

      .css-fm44j {
        -webkit-font-smoothing: antialiased;
        appearance: none;
        font-family:
          RedNum,
          RedZh,
          RedEn,
          -apple-system;
        vertical-align: middle;
        text-decoration: none;
        border: 1px solid rgb(217, 217, 217);
        outline: none;
        user-select: none;
        cursor: pointer;
        display: inline-flex;
        -webkit-box-pack: center;
        justify-content: center;
        -webkit-box-align: center;
        align-items: center;
        margin-right: 16px;
        border-radius: 4px;
        background-color: white;
        color: rgb(38, 38, 38);
        height: 24px;
        font-size: 12px;
      }
    }

    .categorys {
      padding: 0 12px 10px 12px;
    }

    .submit {
      padding: 0 12px 10px 20px;
      margin-top: 10px;

      button {
        width: 80px;
        height: 32px;
        font-size: 14px;
      }

      .publishBtn {
        background-color: #ff2442;
        color: #fff;
        border-radius: 4px;
        cursor: pointer;
      }

      .clearBtn {
        cursor: pointer;
        border-radius: 4px;
        margin-left: 10px;
        border: 1px solid rgb(217, 217, 217);
      }
    }
  }
}
</style>
